package com.example.common.mvvm.viewmodel;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;

import com.blankj.utilcode.util.LogUtils;
import com.example.common.entity.ErrorEntity;
import com.example.common.filed.DataActionEntity;
import com.example.common.mlivedata.LiveDataBus;
import com.example.common.mvvm.repository.BaseRepository;
import com.example.common.utils.ToastUtil;
import com.example.network_skd.BaseEntity;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BaseViewModel<M extends BaseRepository> extends ViewModel implements IViewModel , Observer<BaseEntity> {
    protected M repository;
    private CompositeDisposable compositeDisposable;
    public VMData vmData;
    public BaseViewModel() {
        vmData = new VMData();
        compositeDisposable = new CompositeDisposable();
        initModel();
    }

    @Override
    public void create() {
        initData();
    }

    @Override
    public void destroy() {
        compositeDisposable.dispose();
        compositeDisposable.clear();
    }

    private void initModel(){
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        Class clazz = (Class) genericSuperclass.getActualTypeArguments()[0];
        try {
            repository = (M) clazz.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }








    protected abstract void initData();
    protected abstract void onResult(BaseEntity baseEntity);
    @Override
    public void onSubscribe(@NonNull Disposable d) {
        compositeDisposable.add(d);
    }

    @Override
    public void onNext(@NonNull BaseEntity baseEntity) {
        if (baseEntity instanceof ErrorEntity){
            ErrorEntity entity  = (ErrorEntity) baseEntity;
            ToastUtil.showToast(entity.message);
            return;
        }
        onResult(baseEntity);

    }

    @Override
    public void onError(@NonNull Throwable e) {
        ToastUtil.showToast(e.getMessage());
    }

    @Override
    public void onComplete() {

    }

    public static class VMData {
        public   LiveDataBus<DataActionEntity> uiData;

        public VMData() {
            uiData = new LiveDataBus<>();
        }
        public void post(DataActionEntity dataActionEntity){
            uiData.postValue(dataActionEntity);
        }

    }

}
